package top.txl.controller;

import io.jsonwebtoken.Claims;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.txl.entity.R;
import top.txl.entity.ShoppingCart;
import top.txl.service.LoginService;
import top.txl.service.ShoppingCartService;
import top.txl.utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private LoginService loginService;

    @PostMapping("/add")
    public R<String> addCart(HttpServletRequest request, @RequestBody ShoppingCart cart){

        String jwt = request.getHeader("Authorization");
        log.info("jwt,{},cart,{}",jwt,cart);

        Integer userId = loginService.findUserByToken(jwt);
        if(userId != null){
            cart.setUserId(userId);
        }

        shoppingCartService.addCart(cart);
        return R.success("添加成功");
    }

    @PutMapping("/edit")
    public R<String> editCart(HttpServletRequest request, @RequestBody ShoppingCart cart){
        log.info("修改数量,{}",cart);
        String jwt = request.getHeader("Authorization");
        log.info("jwt,{},cart,{}",jwt,cart);

        Integer userId = loginService.findUserByToken(jwt);
        if(userId != null){
            cart.setUserId(userId);
        }

        shoppingCartService.editCart(cart);
        return R.success("修改成功");
    }

    @PutMapping("/editAll")
    public R<String> editAllCart(HttpServletRequest request){
        log.info("删除购物车数据");
        String jwt = request.getHeader("Authorization");
        log.info("jwt,{}",jwt);

        Integer userId = loginService.findUserByToken(jwt);
        if(userId != null){
            shoppingCartService.deletedAllCartByUserId(userId);
        }

        return R.success("操作成功");
    }

    @GetMapping("/lists")
    public R<List<ShoppingCart>> getCartLists(HttpServletRequest request){
        String jwt = request.getHeader("Authorization");

        Integer userId = loginService.findUserByToken(jwt);

        List<ShoppingCart> lists = shoppingCartService.getCartLists(userId);

        return R.success(lists);
    }
}
